# coding:utf8

from firefly.server.globalobject import netserviceHandle, rootserviceHandle, remoteserviceHandle, GlobalObject, \
    webserviceHandle
from twisted.web import resource
from twisted.python import log
from game.UserManager import UserManager
from servermanager import NEXT_CARD, WuXingHongHui
from twisted.internet import reactor
from game.UserManager import UserManager
from game.models.User import User
from game.share.Message_id import USER_LOGIN_ACTION
import json


def push_message(command_id, data, send_list):
    """
    使用gate 方法向客户端推送消息
    :param command_id:
    :param data:
    :param send_list:
    :return:
    """
    server_name = set([p[0] for p in send_list if p is not None])
    for sn in server_name:
        sdl = filter(lambda x: x[0] == sn, send_list)
        sid = [n[1] for n in sdl]
        log.msg("push message  command_id=%s, msg =%s, sid = %s" % (command_id, data, sid))
        GlobalObject().remote["gate"].callRemote("push_object", command_id, data, send_list)  # 调用父节点推送


def send_all(command_id, data):
    """
    想所有人推送消息
    :param command_id:
    :param data:
    :return:
    """
    keys = UserManager().get_user_list_keys()
    user_list = map(lambda x: [x[0], int(x[1])] if len(x) == 2 and x[1] else None, [x.split(",") for x in keys])
    if user_list:
        push_message(command_id, data, user_list)
    pass


def send_one(command_id, data, session_id):
    """
    向单个人推送消息
    :param command_id:
    :param data:
    :param session_id:
    :return:
    """
    x = session_id.split(",")
    uid = [x[0], int(x[1])] if len(x) == 2 and x[1] else None
    push_message(command_id, data, [uid])


#  初始化五星宏辉
w = WuXingHongHui()
#  初始化推送函数
w.init_send_util(send_all=send_all, send_one=send_one)
#  初始化用户管理器
user_manager = UserManager()


@remoteserviceHandle("gate")
def game_handle_200(data):
    """
    通过remoteserviceHandle("父节点name")
    在此方法内处理 ID 200的 消息
    :param data:
    :return:
    """
    print 'game process gate!!!'
    print data
    return data


@webserviceHandle(url="get_gold_pool")
class GameFireFly(resource.Resource):
    def render(self, request):
        code = request.code

        print code

        method = request.method

        print method

        print request.path

        value = request.args

        print "value=", value
        print "value type=", type(value)

        w.next_card.append(int(value.get("next_card")[0]))
        print "next_card = ", NEXT_CARD
        return "OK"


@webserviceHandle(url="control")
class GameStartHandle(resource.Resource):
    def render(self, request):
        code = request.code
        print code
        method = request.method

        print method
        print request.path
        value = request.args

        print "value=", value
        print "value type=", type(value)
        if int(value.get("status", 999)[0]) == 1:
            if not w.is_start:
                reactor.callLater(2, self.start_game, w)
                return "game will start after 2 second"
            else:
                return "game is starting don't start again!!"
        elif int(value.get("status", 999)[0]) == 0:
            reactor.callLater(2, self.stop_game, w)
            return "game will stop after 2 second"
        else:
            return "params error"

    def start_game(self, w):
        w.is_start = True
        reactor.callWhenRunning(w.test_print, say="game start!!!")

    def stop_game(self, w):
        w.is_start = False


@remoteserviceHandle("gate")
def forwarding_remote(key, session_id, data={}):
    print "key", key
    print "session_id", session_id
    print "data", data


def event_login(session_id, command_id, request_proto):
    print "event_login!!"
    user_id = request_proto.get("user_id")
    user_pass= request_proto.get("password")
    user = User("", user_id, session_id)
    user_manager.add_user(user)



def process_net_message(session_id, command_id, request_proto):
    """
    处理所有消息 分发
    :param session_id:
    :param command_id:
    :param request_proto:
    :return:
    """

    if command_id == USER_LOGIN_ACTION:
        event_login()
